#ifndef CLIENT_H
#define CLIENT_H

#include <stdio.h>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>

#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <thread>

#include "Tools.h"
#include "RtpHandler.h"
#include "FlvWriter.h"

#define WAIT_MESSAGE 500
#define BUFF_SIZE 1600

class Client
{
private:
    //解析输入的rul
    bool UrlParse(const char* url);
    
    //初始化流媒体客户端套接字
    bool ClientInit();

    //RTSP的Option方法
    bool SendOption();

    //RTSP的Describe方法
    bool SendDescribe();
    
    //RTSP的Setup方法
    bool SendSetup();
    
    //RTSP的Setup方法
    bool ClientListen(int flvPort, const std::string& flvUrl);

    //RTSP的Play方法
    bool SendPlay();

    //RTSP的Pause方法
    bool SendPause();

    //RTSP的TearDown方法
    bool SendTearDown();

    //RTSP的TearDown方法
    void StartConvert();

    //定时退出线程
    static void TimerThread(int port);

    //计算md5鉴权结果
    std::string ComputeRes(const std::string& cmd);

public:
    Client(const char* _url, int _flvPort, const std::string& _flvUrl, bool& noError);
    ~Client();

private:
    const char* sep = "\n";

    //流地址信息
    std::string IP;
    int port;
    std::string userName;
    std::string pwd;
    std::string urlWithoutUser;

    //套接字信息
    int rtspSocketFd;
    int flvServerSocketFd;
    int flvClientSocketFd;

    //rtsp交互信息
    int sendSeq;
    int recvSeq;
    int code;
    std::string userAgant;
    char* sessionID;
    char sendBuff[BUFF_SIZE] = { 0 };
    char recvBuff[BUFF_SIZE] = { 0 };
    float frameRate;

    //rtsp权限信息
    std::string realm;
    std::string nonce;
    std::string authPre;

    //rtsp辅助信息
    std::string vedioTrack;
    std::string session;

    //rtp解析器
    RtpHandler* rtpHandler;
    int curBufferIndex;//当前的缓冲区起始点补偿
    int bytesReceived;//接收数据包的长度

    //rtp数据接收
    char flvTagData[REC_BUFFER_LENGTH_FLV];//超长的循环接收缓冲区
    std::thread* flvThread;

    //flv写入
    FlvWriter* flvWriter;
};

#endif